package com.jiangcheng.demo.service.impl;

import com.jiangcheng.demo.entity.User;
import com.jiangcheng.demo.mapper.UserMapper;
import com.jiangcheng.demo.qcloud.CosClient;
import com.jiangcheng.demo.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiangcheng.demo.utils.LoginVo;
import com.jiangcheng.demo.utils.NewResult;
import com.jiangcheng.demo.utils.Result;
import com.jiangcheng.demo.utils.TokenUtil;
import com.sun.org.apache.xpath.internal.operations.Bool;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Random;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author admin
 * @since 2021-07-15
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    UserMapper userMapper;
    @Autowired
    CosClient cosClient;

    //application.properties中已配置的值
    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private JavaMailSender mailSender;//一定要用@Autowired

    // 登录功能
    public Result login(User user){
        System.out.println(user.getUsername());
        User result_user = userMapper.selectByName(user.getUsername());
        System.out.println("查询到的用户:" + result_user);
        if (result_user == null){
            return new Result(400,false, "此用户不存在");
        }
        if (!result_user.getPassword().equals(user.getPassword())){
            return new Result(400,false, "密码错误");
        }
        // 获取token
        String token = TokenUtil.getToken(result_user);
        LoginVo loginVo = new LoginVo();
        BeanUtils.copyProperties(result_user,loginVo);
        loginVo.setToken(token);
        System.out.println(loginVo);

        return new Result(200,true, "登录成功",loginVo);
    }

    // 注册功能
    public Result register(User user){
        User result_user = userMapper.selectByName(user.getUsername());
        System.out.println(user);
        if (result_user != null){
            return new Result(400,false, "此用户已存在");
        }
        if (user.getEmail() != null){
            User result = userMapper.selectByEmail(user.getEmail());
            if (result != null){
                return new Result(400,false, "此邮箱已注册");
            }
        }

        int insert = userMapper.insert(user);
        if (insert != 1){
            return new Result(400,false, "网络故障");
        }

        return new Result(200,true, "注册成功");
    }

    @Override
    public NewResult updateUserPicById(String picPath, Integer uId) {
        Integer result = userMapper.UpdateUserPicById(uId, picPath);
        if (result == 1){
            return new NewResult(200,true,"上传成功");
        }
        return new NewResult(400,false,"上传失败");
    }

    // 上传用户图片
//    public NewResult uploadUserPic(Integer uId, MultipartFile file) throws IOException {
//        System.out.println("uId:" + uId);
//        // 上传图片到cos 拿到对应图片途径
//        String pic_path = cosClient.uploadFile(file);
//        System.out.println(pic_path);
//        if (pic_path != null) {
//            // 拿到对应图片路径 再根据传过来的用户id把图片地址添加到数据库当中
//            Integer result = userMapper.UpdateUserPicById(uId,pic_path);
//            if (result == 1){
//                return new NewResult(200,true,"上传成功",pic_path);
//            }
//        }
//
//        return new NewResult(400,false,"上传失败",pic_path);
//    }

    /**
     * 发送邮箱验证码
     * @param email
     * @param httpSession
     * @return
     */
    @Override
    @Async
    public String sendMimeMail(String email, HttpSession httpSession) {
        try {
            SimpleMailMessage mailMessage = new SimpleMailMessage();

            mailMessage.setSubject("验证码");//主题
            //生成随机数
            String code = randomCode();

            //将随机数放置到session中
            httpSession.setAttribute("email",email);
            httpSession.setAttribute("code",code);
            mailMessage.setText("您收到的验证码是："+code);//内容
            System.out.println(httpSession.getAttribute("code"));
            mailMessage.setTo(email);//发给谁

            mailMessage.setFrom(from);//你自己的邮箱
            System.out.println("emai:" + email);
            mailSender.send(mailMessage);//发送
            return httpSession.getId();
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }

    }

    @Override
    public Result emailLogin(User user) {
        User result_user = userMapper.selectByEmail(user.getEmail());
        System.out.println("查询到的用户:" + result_user);
        if (result_user == null){
            return new Result(400,false, "此邮箱未注册");
        }
        if (!result_user.getPassword().equals(user.getPassword())){
            return new Result(400,false, "密码错误");
        }
        // 获取token
        String token = TokenUtil.getToken(result_user);
        LoginVo loginVo = new LoginVo();
        BeanUtils.copyProperties(result_user,loginVo);
        loginVo.setToken(token);

        return new Result(200,true, "登录成功",loginVo);
    }

    @Override
    public NewResult updateUsernameById(String username,Integer uId) {
        User result_user = userMapper.selectByName(username);
        if (result_user != null){
            return new NewResult(400,false, "此用户已存在");
        }

        int result = userMapper.updateUsernameById(username,uId);

        if (result != 1) {
            return new NewResult(400,false,"修改失败");
        }
        return new NewResult(200,true,"修改成功");
    }

    @Override
    public NewResult updatePasswordByUid(String password, Integer uId) {
        int result = userMapper.updatePasswordById(password,uId);

        if (result != 1) {
            return new NewResult(400,false,"修改失败");
        }
        return new NewResult(200,true,"修改成功");
    }

    @Override
    public NewResult findUserById(Integer id) {
        User user = userMapper.selectById(id);
        if (user != null) {
            return new NewResult(200,true,"查询成功", user);
        }
        return new NewResult(400,false,"查询失败");
    }

    /**
     * 随机生成6位数的验证码
     * @return String code
     */
    public String randomCode(){
        StringBuilder str = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            str.append(random.nextInt(10));
        }
        return str.toString();
    }

}
